<template>
  <div :class="extendClass" class="upload_box upload_btn click_to_green">
    <x-img :src="img" :default-src="defaultImg" @click.native="selectPicture" v-if="isWx"/>

    <x-img 
          :src="img"
          :default-src="defaultImg" v-if="!isWx"
        />
    <input
      v-if="!isWx"
      ref="uploadFile"
      @change="onChange"
      type="file"
      accept="image/*"
      class="upload_file_input"
    >

  </div>
</template>

<script>
import baseService from "../shared/service/baseService";
import { fileUtil } from "../assets/js/fileUtil";
import * as qiniu from "qiniu-js";
import { XImg } from "vux";
import weixinService from "../shared/service/weixinService";
const wx = require("weixin-js-sdk");

export default {
  components: {
    XImg
  },
  name: "imgUpload",
  props: [
    "imgSrc",
    "width",
    "height",
    "defaultSrc",
    "extClass"
  ], /* uploadOkEvent 文件上传完成事件 */
   data() {
    var img="";
    if (this.src) {
      img = this.src;
    }
    var defaultImg = img;
    if(this.defaultSrc){
        defaultImg = this.defaultSrc;
    }
    var extendClass = "";
    if(this.extClass){
        extendClass = this.extClass;
    }
    var isWx =  navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1;
    return {
      isWx:isWx,
      img:img,
      defaultImg:defaultImg,
      extendClass:extendClass,
      domain: "",
      token: "",
      w: this.width || "5rem",
      h: this.height || "5rem",
      config: {
        useCdnDomain: true,
        disableStatisticsReport: false,
        retryCount: 6,
        region: qiniu.region.z0
      },
      putExtra: {
        fname: "",
        params: {},
        mimeType: null
      }
    };
  },
  created() {
    this.getDomain();
    this.getToken();
    this.initWx();
  },
  methods: {
    initWx() {
      var that = this;
      var url = location.href;
   //   alert("this.$cookie.getAppid()"+this.$cookie.getAppid());
      if(!this.$cookie.getAppid()){
           that.isWx=false;
           return;
      }
      weixinService.getSignature(url).then(res => {
        if (res.data) {
          var data = res.data;
          wx.config({
            debug: false,
            appId: data.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名，见附录1
            jsApiList: ["chooseImage"] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
          });

          wx.error(function(res){
              that.isWx=false;
          });
        }
      });
    },
    selectPicture: function() {
      var defaultNum = 1;
      try {
        if (this.$parent.$parent.$parent.getImgUploadNum) {
          var imgUploadNum = this.$parent.$parent.$parent.getImgUploadNum();
          defaultNum = imgUploadNum;
        }
      } catch (e) {}

      let that = this;
     
      wx.ready(function() {
        wx.chooseImage({
          count: defaultNum, // 默认9
          sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
          success: function(resImage) {
            var localIds = resImage.localIds;
            if(localIds.length>0){
               that.$vux.loading.show();
              that.readyImg(localIds, 0);
            }else{
              that.$vux.loading.hide();
            }
          },
          error: function(res) {
            alert(res);
          }
        });
      });
    },
    readyImg(localIds, index) {
      let obj = { localId: localIds[index], base64Data: "", url: "" };
      let that = this;
      wx.getLocalImgData({
        localId: localIds[index],
        success: function(res) {
          var localData = res.localData;
          if (window.__wxjs_is_wkwebview) {
            // 如果是IOS，需要去掉前缀
          } else {
            //android
            localData = "data:image/png;base64," + localData;
          }
          obj.base64Data = localData;
          if(index<localIds.length-1){
            that.readyImg(localIds, index+1);
          }
          that.uploadFile(obj, 1);
        }
      });
    },
    getDomain() {
      baseService.qiniuDomain().then(res => {
        this.domain = res.data;
      });
    },
    getToken() {
      baseService.qiniuToken().then(res => {
        this.token = res.data;
      });
    },
    setImgSrc(src) {
      this.img = src;
    },
    uploadFile: function(fileObj, type) {
      //type:1 是图片，type:2 是附件
      try {
        var formData = new FormData();
        var that = this;
        let name = "";
        if (type == 2) {
          name = fileObj.name;
        }

        formData.append("token", this.token);

        if (type == 1) {
          formData.append(
            "file",
            this.$commonUtil.convertImgDataToBlob(fileObj.base64Data)
          );
        } else if (type == 2) {
          formData.append("file", fileObj.file);
        }

        formData.append(
          "key",
          "wx/3ndclassroom/" + this.$commonUtil.uuid() + name
        );
        $.ajax({
          url: "http://upload.qiniup.com",
          type: "POST",
          data: formData,
          cache: false,
          processData: false,
          contentType: false,
          success: function(data) {
            if (type == 1) {
              fileObj.url = that.domain + data.key;
            } else if (type == 2) {
              fileObj.url = that.domain + data.key;
            }
            that.$vux.loading.hide();
            that.$emit("uploadOkEvent", fileObj.url);
          },
          error: function(responseStr) {
            // console.log("====responseStr",responseStr)
            that.$vux.loading.hide();
            that.showToast = true;
            that.message = "上传图片失败,请重试";
          }
        });
      } catch (e) {
        alert(e);
      }
    },
    upload(file) {
      let observable;
      if (file) {
        const key = file.name;
        this.putExtra.params["x:name"] = key.split(".")[0];

        //文件上传事件
        const error = () => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "提示",
            content: "上传出错，请重试！"
          });
        };
        //文件上传事件
        const complete = res => {
          this.$vux.loading.hide();
          if (res.key && res.key.match(/\.(jpg|jpeg|png|gif)$/)) {
            var src = this.domain + res.key;
            this.$emit("uploadOkEvent", src);
          }
        };

        const subObject = {
          // next: next,
          error: error,
          complete: complete
        };
        // 调用sdk上传接口获得相应的observable，控制上传和暂停
        observable = qiniu.upload(
          file,
          key,
          this.token,
          this.putExtra,
          this.config
        );
        // 上传
        this.$vux.loading.show({ text: "Loading" });
        observable.subscribe(subObject);
      }
    },
    onChange() {
      const file = event.target.files[0];
      this.upload(file);
      //大于1025kb 的文件压缩一下
      //   fileUtil.getCompress(file,{size:1025},this.upload);
    }
  }
};
</script>

<style scoped>
</style>